package com.kye.express.business.waybill_take_photo.yunmai;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.utils.ImageUtils;
import com.kye.express.utils.StringUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.UserSession;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.waybill_take_photo.PhotograghWaybillResultBean;
import com.kye.model.bean.waybill_take_photo.ValidateWaybillUploadResultBean;
import com.kye.model.bean.waybill_take_photo.WaybillPhotograhbean;
import com.kye.model.constant.Constants;
import com.kye.rxcodescanner.Decode;
import com.kye.rxcodescanner.DecodeFormatManager;
import com.yunmai.cc.smart.eye.controler.CameraManager;
import com.yunmai.cc.smart.eye.controler.OcrManager;
import com.yunmai.cc.smart.eye.util.UtilApp;
import com.yunmai.cc.smart.eye.vo.ResultInfo;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 视频识别类
 *
 * @author fangcm 2013-03-18
 */

public class CameraActivity extends BaseAppCompatActivity implements SurfaceHolder.Callback, CameraActivityContract.CameraActivityView {

    private final String TAG = "cc_smart";
    public static final String ARG_DATA = "imageList";
    public static final String ARG_DATA_RESULT = "photograghList";

    private int rateTime = 100;//类型错误
    private int startTime = 800;
    private int goonTime = 100; //识别失败后继续
    private int rightNow = 100; //结果为空 或者模糊时 立刻进行下次识别
    private int rightNow2 = 600; //结果为空 或者模糊时 立刻进行下次识别

    private SurfaceView sv_preview;
    private SurfaceHolder surfaceHolder;
    private CameraManager cameraManager;
    private boolean autoFoucs = false;
    private ViewfinderView finderView;
    private boolean preview = true;
    ;
    private OcrManager ocrManager;
    private Rect rect, rect_pthoto;
    private ImageView iv;
    private ProgressBar progressBar;
    private boolean isBlurOn = true;//模糊判断是否打开
    private boolean isManaulIn = false;//是否正在执行手动拍摄
    private boolean isAutoIn = false;//是否正在执行手动拍摄
    private boolean cameraError = false;

    private WindowManager manager;
    private Display display;
    private RotateImageView btnFlash, btnCancel;
    private TextView tipView;
    private LayoutParams btn_FlashParams, btn_CancelParams, tip_Params;
    private int btWidth;
    private int textWidth;
    private String tip = "";
    private int textSize = 20;
    private int color = Color.WHITE;
    private int nDisplayWidth, nDisplayHeight;
    private long startRecogTime;
    long startBCRTime;    //	初始化时间

    private List<WaybillPhotograhbean> imageList;
    private Intent resultIntent;
    private List<WaybillPhotograhbean> photograghList;
    private String filePath = getSdcardDir() + "/" + "kyeWaybill";
    private String pictruePath;
    private int lastNumber;//用来判断时候有重新拍同一张运单  然后删除
    private WaybillPhotograhbean lastWaybillPhotograhbean;//用来判断时候有重新拍同一张运单  然后删除
    private String waybillCode;
    private RelativeLayout ivRemake;
    private RelativeLayout ivContinue;
    private LinearLayout navigationBar;
    private RelativeLayout rlPrompt, rlTakepho;
    private ImageView tvLight;//灯按钮
    private ImageView ivAutomatic;//自动  手动
    private ImageView ivFinishImage;//拍完照显示图片
    private boolean isAutomatic = true;//按钮自动或者手动状态
    private boolean isStop = false;//相机是否在预览
    private TextView mTvErrorMsg;
    private Toast toast;
    private final int mBlurImage = 4;//  模糊判断值   传 4 或者 8
    private final int mImageCompress = 50;//图片压缩数值

    private RelativeLayout mContainer;
    private RelativeLayout mCropLayout;
    private CameraActivityContract.CameraActivityViewPresenter mPresenter;
    private String mCurrentWaybill = "";
    private Dialog mKyeDialog;

    private String getSdcardDir() {
        File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + Constants.SDCARD_FOLDER_NAME);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        return fileDir.getAbsolutePath();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            ToastManager.show(getBaseContext(), "请插入存储卡", Toast.LENGTH_LONG);
            finish();
        }
        File file = new File(UtilApp.completeManagePath());
        if (!file.exists()) {
            file.mkdirs();
        }

        manager = (WindowManager) getBaseContext().getSystemService(
                Context.WINDOW_SERVICE);
        display = manager.getDefaultDisplay();
        nDisplayWidth = display.getWidth();
        nDisplayHeight = display.getHeight();
        // 有些手机返回的屏幕高和宽不固定
        if (nDisplayWidth < nDisplayHeight) {
            int w = nDisplayWidth;
            nDisplayWidth = nDisplayHeight;
            nDisplayHeight = w;
        }
        Log.e("QINBO", "DISPLAY_w:" + nDisplayWidth + "  DISPLAY_y:"
                + nDisplayHeight);
        textWidth = nDisplayHeight * 2 / 3;
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            tip = bundle.getString(UtilApp.CONTENT_TIP_INTENT);
            if (tip == null) tip = "";
            textSize = bundle.getInt(UtilApp.SIZE_TIP_INTENT);
            color = bundle.getInt(UtilApp.COLOR_TIP_INTENT);
            textWidth = bundle.getInt(UtilApp.WIDTH_TIP_INTENT);
            if (textSize <= 0)
                textSize = 20;
            if (textWidth <= 0)
                textWidth = nDisplayHeight * 2 / 3;
            if (color == 0)
                color = Color.WHITE;
        }
        setContentView(initView());
        mPresenter = new CameraActivityContract.CameraActivityViewPresenter(this);
        mPresenter.bind(this);
        cameraManager = new CameraManager(getBaseContext(), mHandler);
        mCameraOpenThread.start();
        try {
            mCameraOpenThread.join();
            mCameraOpenThread = null;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            cameraError = true;
        }
        if (cameraError) {
            ToastManager.show(getBaseContext(), "照相机未启动！请在设置中 打开相机权限!", Toast.LENGTH_SHORT);
            finish();
            return;
        }
        setParameters();
        loadData();
        initCamera();
    }

    public void initCamera() {
        cameraManager.initDisplay();
        isAutoIn = false;
        isManaulIn = false;
        mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, startTime);
    }

    private void loadData() {
        imageList = (List<WaybillPhotograhbean>) getIntent().getSerializableExtra(ARG_DATA);
        if (!UserSession.getInstance().getUser().isLogin()) {
            finish();
            return;
        }
        resultIntent = new Intent();
        photograghList = new ArrayList<WaybillPhotograhbean>();
        photograghList.addAll(imageList);
        resultIntent.putExtra(ARG_DATA_RESULT, (Serializable) photograghList);
        setResult(RESULT_OK, resultIntent);

        ViewTreeObserver vto = navigationBar.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {//计算空间的宽
            @Override
            public void onGlobalLayout() {
                navigationBar.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                finderView.setDistance(navigationBar.getWidth());
            }
        });
    }

    private void validate(ResultInfo resultInfo) {
        if (photograghList.size() >= 9) {
            showHorizontalDialog("一次最多只能传9张哦", hideCancle, true, "取消", "确定");
            return;
        }
        PhotograghWaybillResultBean photoResult = null;
        try {
            photoResult = new Gson().fromJson(resultInfo.getResult().toString().trim(), new TypeToken<PhotograghWaybillResultBean>() {
            }.getType());
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            showHorizontalDialog("未能识别的运单，请重新拍照", hideCancle, true, "取消", "确定");
            return;
        }
        if (photoResult == null) {
            showHorizontalDialog("未能识别的运单，请重新拍照", hideCancle, true, "取消", "确定");
            return;
        }
        Logger.d(resultInfo.getImgPath());
        if (!TextUtils.isEmpty(resultInfo.getImgPath())){
           Bitmap bitmap = ImageUtils.getBitmap(resultInfo.getImgPath());
            Object decodeFormats = DecodeFormatManager.CODE_128_FORMATS;
            Decode decode = new Decode((Collection)decodeFormats);
            try {
                Result result = decode.decode(bitmap);
                if (result != null){
                  String resultCode =  result.getText();
                  if (!TextUtils.isEmpty(resultCode)){
                      waybillCode = resultCode;
                  }
                }
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
        }

//        if (TextUtils.isEmpty(waybillCode)) {
//            waybillCode = photoResult.getBcode();
//        }
        if (StringUtils.isNullOrEmpty(waybillCode)) {
            showHorizontalDialog("未能识别的运单，请重新拍照", hideCancle, true, "取消", "确定");
            return;
        }

        rlPrompt.setVisibility(View.GONE);
        rlTakepho.setVisibility(View.GONE);
        for (int i = 0; i < photograghList.size(); i++) {
            if (waybillCode.equals(photograghList.get(i).getWaybillNumber())) {
                lastNumber = i;
                lastWaybillPhotograhbean = photograghList.get(i);
                showHorizontalDialog("运单已存在，是否覆盖？", showCancle, true, "取消", "确定");
                return;
            }
        }
        isStop = true;
        verificationWaybill(waybillCode);
    }

    private Dialog mDialog;
    private final int hideCancle = 10;
    private final int showCancle = 8;

    /**
     * @param mContent
     * @param type     是否隐藏左边按钮
     * @param isDelet  隐藏左边按钮后点击确定是否删除图片
     * @param leftStr
     * @param rightStr
     */
    private void showHorizontalDialog(String mContent, final int type, final boolean isDelet, String leftStr, String rightStr) {
        View mDialogView = LayoutInflater.from(this).inflate(R.layout.dialog_waybill_photogragh_h, null);
        TextView content = (TextView) mDialogView.findViewById(R.id.tv_waybill_photogragh_content);
        RelativeLayout cancle = (RelativeLayout) mDialogView.findViewById(R.id.rl_waybill_photogragh_cancle);
        RelativeLayout sure = (RelativeLayout) mDialogView.findViewById(R.id.rl_waybill_photogragh_sure);
        content.setText(mContent);
        mDialog = new AlertDialog.Builder(this).create();
        if (type == hideCancle) {
            cancle.setVisibility(View.GONE);
        } else {
            cancle.setVisibility(View.VISIBLE);
        }
        mDialog.setCancelable(false);
        mDialog.show();
        mDialog.setContentView(mDialogView);

        cancle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
                isStop = false;
                ImageUtils.deleteFile(pictruePath);
                tipView.setVisibility(View.VISIBLE);
                if (isAutomatic) {
                    rlPrompt.setVisibility(View.VISIBLE);
                    rlTakepho.setVisibility(View.GONE);
                } else {
                    rlPrompt.setVisibility(View.GONE);
                    rlTakepho.setVisibility(View.VISIBLE);
                }
                tipView.setText(tip.equalsIgnoreCase("") ? "请将快递单正面置于此区域尝试对齐边缘" : tip);
                cameraManager.initDisplay();
                isAutoIn = false;
                isManaulIn = false;
                mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, startTime);
                finderView.setLineRect(0);
            }
        });
        sure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
                isStop = false;
                if (type == hideCancle) {
                    if (isDelet) {
                        ImageUtils.deleteFile(pictruePath);
                    }
                    tipView.setVisibility(View.VISIBLE);
                    if (isAutomatic) {
                        rlPrompt.setVisibility(View.VISIBLE);
                        rlTakepho.setVisibility(View.GONE);
                    } else {
                        rlPrompt.setVisibility(View.GONE);
                        rlTakepho.setVisibility(View.VISIBLE);
                    }
                    tipView.setText(tip.equalsIgnoreCase("") ? "请将快递单正面置于此区域尝试对齐边缘" : tip);
                    cameraManager.initDisplay();
                    isAutoIn = false;
                    isManaulIn = false;
                    mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, startTime);
                    finderView.setLineRect(0);
                    return;
                }
                ImageUtils.deleteFile(lastWaybillPhotograhbean.getImagePath());
                WaybillPhotograhbean waybillPhotograhbean = new WaybillPhotograhbean();
                waybillPhotograhbean.setId(startRecogTime);
                waybillPhotograhbean.setImagePath(pictruePath);
                waybillPhotograhbean.setWaybillNumber(waybillCode);
                photograghList.remove(lastNumber);
                photograghList.add(waybillPhotograhbean);

                tipView.setVisibility(View.VISIBLE);
                if (isAutomatic) {
                    rlPrompt.setVisibility(View.VISIBLE);
                    rlTakepho.setVisibility(View.GONE);
                } else {
                    rlPrompt.setVisibility(View.GONE);
                    rlTakepho.setVisibility(View.VISIBLE);
                }
                tipView.setText(tip.equalsIgnoreCase("") ? "请将快递单正面置于此区域尝试对齐边缘" : tip);
                cameraManager.initDisplay();
                isAutoIn = false;
                isManaulIn = false;
                mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, startTime);
                finderView.setLineRect(0);
            }
        });
    }

    private void verificationWaybill(final String waybill) {
        mCurrentWaybill = waybill;
        mPresenter.validateWaybillUpload(waybill);
    }

    private Handler catchHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            finish();
            return;
        }
    };
    private Thread mCameraOpenThread = new Thread(new Runnable() {
        public void run() {
            try {
                cameraManager.openCamera();
            } catch (Exception e) {
                cameraError = true;
                e.printStackTrace();
                catchHandler.sendEmptyMessage(0);
            }
        }
    });


    private void setParameters() {
        cameraManager.setCameraFlashModel(Camera.Parameters.FLASH_MODE_OFF);
        isBlurOn = cameraManager.isSupportAutoFocus();
        cameraManager.setPreviewSize(display);

        int pWidth = cameraManager.getPreviewWidth();
        int pHeight = cameraManager.getPreviewHeight();
        if (pWidth == 0 || pHeight == 0) {
            ToastManager.show(getBaseContext(), "照相机未启动！", Toast.LENGTH_SHORT);
            finish();
            return;
        }

        WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        int wWidth = display.getWidth();
        int wHeight = display.getHeight();
        if (android.os.Build.MANUFACTURER.equals("Lenovo") && android.os.Build.MODEL.equals("IdeaTabS2110AH")) {
            wHeight = 800;
        }

        int tempWidth = pWidth;
        int tempHeidht = pHeight;
        float x = 100.0f;
        int tempW = pWidth;
        int tempH = pHeight;
        if (wWidth > pWidth && wHeight > pHeight) {
            while (wWidth > tempW && wHeight > tempH) {
                x++;
                tempW = (int) (pWidth * x / 100.0);
                tempH = (int) (pHeight * x / 100.0);
                if (wWidth > tempW && wHeight > tempH) {
                    tempWidth = tempW;
                    tempHeidht = tempH;
                }
            }
        } else {
            while (tempWidth > wWidth || tempHeidht > wHeight) {
                x--;
                tempWidth = (int) (pWidth * x / 100.0);
                tempHeidht = (int) (pHeight * x / 100.0);
            }
        }

//		tempWidth = 854;
//		tempHeidht = 480;
        ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) sv_preview.getLayoutParams();
        lp.width = tempWidth;
        lp.height = tempHeidht;
        sv_preview.getHolder().setFixedSize(tempWidth, tempHeidht);
        sv_preview.setLayoutParams(lp);

        surfaceHolder = (SurfaceHolder) sv_preview.getHolder();
        surfaceHolder.addCallback(CameraActivity.this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        finderView.initFinder(tempWidth, tempHeidht, mHandler);
    }


    @SuppressLint("WrongConstant")
    private View initView() {
        RelativeLayout rl_body = new RelativeLayout(getBaseContext());
        LayoutParams body_LayoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        rl_body.setLayoutParams(body_LayoutParams);
        sv_preview = new SurfaceView(getBaseContext());
        LayoutParams sv_LayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        sv_LayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        sv_preview.setLayoutParams(sv_LayoutParams);
        rl_body.addView(sv_preview);
        iv = new ImageView(getBaseContext());
        LinearLayout.LayoutParams iv_LayoutParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        iv.setLayoutParams(iv_LayoutParams);
        iv.setScaleType(ScaleType.FIT_XY);
        iv.setVisibility(View.GONE);
        rl_body.addView(iv);
        finderView = new ViewfinderView(getBaseContext());

        BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(
                R.drawable.flash_on_s);
        btWidth = bd.getBitmap().getWidth();
        View yunmaiView = View.inflate(getBaseContext(), R.layout.activity_waybill_yunmai, null);
        navigationBar = (LinearLayout) yunmaiView.findViewById(R.id.ll_yunmai_function);
        RelativeLayout rlFinderView = (RelativeLayout) yunmaiView.findViewById(R.id.rl_yunmai_finder_view);
        tvLight = (ImageView) yunmaiView.findViewById(R.id.openLight);
        mTvErrorMsg = (TextView) yunmaiView.findViewById(R.id.tv_yunmai_error_msg);
        ImageView ivCancel = (ImageView) yunmaiView.findViewById(R.id.iv_waybill_photogragh_close);
        ImageView remake = (ImageView) yunmaiView.findViewById(R.id.iv_waybill_yunmai_remake);
        ImageView continu = (ImageView) yunmaiView.findViewById(R.id.iv_waybill_yunmai_continue);
        ImageView ivTakepho = (ImageView) yunmaiView.findViewById(R.id.iv_waybill_yunmai_takepho);
        ivFinishImage = (ImageView) yunmaiView.findViewById(R.id.iv_yunmai_photogrgh_finish);
        ivAutomatic = (ImageView) yunmaiView.findViewById(R.id.iv_waybill_yunmai_automatic);
        ivRemake = (RelativeLayout) yunmaiView.findViewById(R.id.tv_waybill_remake);
        ivContinue = (RelativeLayout) yunmaiView.findViewById(R.id.tv_waybill_continue);
        rlPrompt = (RelativeLayout) yunmaiView.findViewById(R.id.tv_waybill_prompt);
        rlTakepho = (RelativeLayout) yunmaiView.findViewById(R.id.tv_waybill_takepho);
        mContainer = (RelativeLayout) yunmaiView.findViewById(R.id.rl_yunmai_camere);
        mCropLayout = (RelativeLayout) yunmaiView.findViewById(R.id.yunmai_capture_crop_layout);
        ivAutomatic.setImageResource(R.drawable.waybill_potogragh_manual);

        continu.setTag("contiue");
        remake.setTag("remake");
        tvLight.setTag("falsh");
        ivCancel.setTag("cancel");
        ivAutomatic.setTag("automatic");
        ivTakepho.setTag("takepho");
        tvLight.setOnClickListener(initClickListener());
        ivCancel.setOnClickListener(initClickListener());
        continu.setOnClickListener(initClickListener());
        remake.setOnClickListener(initClickListener());
        ivAutomatic.setOnClickListener(initClickListener());
        ivTakepho.setOnClickListener(initClickListener());
        rl_body.addView(finderView);
        rl_body.addView(yunmaiView);

        progressBar = new ProgressBar(getBaseContext());
        LayoutParams pb_LayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        pb_LayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        progressBar.setLayoutParams(pb_LayoutParams);
        progressBar.setScrollBarStyle(ProgressBar.SOUND_EFFECTS_ENABLED);
        progressBar.setVisibility(View.GONE);
        rlFinderView.addView(progressBar);

        tipView = new TextView(getBaseContext());
        tip_Params = new LayoutParams(textWidth, LayoutParams.WRAP_CONTENT);
        tip_Params.addRule(RelativeLayout.CENTER_IN_PARENT);
        tipView.setGravity(Gravity.CENTER);
        tipView.setLayoutParams(tip_Params);
        tipView.setText(tip.equalsIgnoreCase("") ? "请将快递单正面置于此区域尝试对齐边缘" : tip);
        tipView.setTextSize(textSize);
        tipView.setTextColor(color);
        rlFinderView.addView(tipView);
        return rl_body;
    }

    private boolean isFlashOn = false;

    private OnClickListener initClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v.getTag().equals("falsh")) {
                    if (isFlashOn) {
                        if (cameraManager.closeFlashlight()) {
                            tvLight.setSelected(false);
                            isFlashOn = false;
                        }
                    } else {
                        if (cameraManager.openFlashlight()) {
                            tvLight.setSelected(true);
                            isFlashOn = true;
                        }
                    }
                } else if (v.getTag().equals("cancel")) {
                    finish();
                } else if (v.getTag().equals("contiue")) {
                    isStop = false;
                    tipView.setVisibility(View.VISIBLE);
                    ivRemake.setVisibility(View.GONE);
                    ivContinue.setVisibility(View.GONE);
                    ivFinishImage.setVisibility(View.GONE);
                    if (isAutomatic) {
                        rlPrompt.setVisibility(View.VISIBLE);
                        rlTakepho.setVisibility(View.GONE);
                    } else {
                        rlPrompt.setVisibility(View.GONE);
                        rlTakepho.setVisibility(View.VISIBLE);
                    }
                    tipView.setText(tip.equalsIgnoreCase("") ? "请将快递单正面置于此区域尝试对齐边缘" : tip);
                    cameraManager.initDisplay();
                    isAutoIn = false;
                    isManaulIn = false;
                    mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, goonTime);
                    finderView.setLineRect(0);
                } else if (v.getTag().equals("remake")) {
                    isStop = false;
                    tipView.setVisibility(View.VISIBLE);
                    ivRemake.setVisibility(View.GONE);
                    ivContinue.setVisibility(View.GONE);
                    ivFinishImage.setVisibility(View.GONE);
                    if (isAutomatic) {
                        rlPrompt.setVisibility(View.VISIBLE);
                        rlTakepho.setVisibility(View.GONE);
                    } else {
                        rlPrompt.setVisibility(View.GONE);
                        rlTakepho.setVisibility(View.VISIBLE);
                    }
                    tipView.setText(tip.equalsIgnoreCase("") ? "请将快递单正面置于此区域尝试对齐边缘" : tip);
                    if (photograghList.size() > 0) {
                        photograghList.remove(photograghList.size() - 1);
                    }
                    ImageUtils.deleteFile(pictruePath);
                    cameraManager.initDisplay();
                    isAutoIn = false;
                    isManaulIn = false;
                    mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, startTime);
                    finderView.setLineRect(0);
                } else if (v.getTag().equals("automatic")) {//自动  手动拍照
                    if (isAutomatic) {//手动
                        manulRemove();
                        if (!isStop) {
                            rlPrompt.setVisibility(View.GONE);
                            rlTakepho.setVisibility(View.VISIBLE);
                        }
                        ivAutomatic.setImageResource(R.drawable.waybill_potogragh_automatic);
                        isAutomatic = false;
                        finderView.setLineRect(0);
                    } else {//自动
                        finderView.setLineRect(0);
                        if (!isStop) {
                            rlPrompt.setVisibility(View.VISIBLE);
                            rlTakepho.setVisibility(View.GONE);
                        }
                        ivAutomatic.setImageResource(R.drawable.waybill_potogragh_manual);
                        isAutomatic = true;
                        mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, rightNow);
                    }
                } else if (v.getTag().equals("takepho")) {
                    if (mHandler != null) {
                        isAutoIn = false;
                        isManaulIn = false;
                        mHandler.sendEmptyMessage(UtilApp.CAMERA_TAKE_PHOTO_3);
                    }
                }
            }
        };
    }

    private void manulRemove() {
        mHandler.removeMessages(UtilApp.RECOGN_OK);
        mHandler.removeMessages(UtilApp.RECOGN_FAIL);
        mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO);
        mHandler.removeMessages(UtilApp.START_AUTOFOCUS);
        mHandler.removeMessages(UtilApp.ONLY_AUTOFOCUS);
        mHandler.removeMessages(UtilApp.LOAD_PIC);
        mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_ERROR);
        mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_OK);
        mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_DATA_OK);
        mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_2);
        mHandler.removeMessages(UtilApp.RECOGN_LINE_NULL);
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UtilApp.RECOGN_TAKE_PIC_OK_2:
                    Logger.d("RECOGN_TAKE_PIC_OK_2");
                    if (isManaulIn) {
                        return;
                    }
                    if (ocrManager == null) {
                        ocrManager = new OcrManager();
                        ocrManager.setBlurImage(mBlurImage, mImageCompress);
                        rect = cameraManager.getViewfinder(finderView.getFinder());
                        rect_pthoto = cameraManager.getRectByPhoto(finderView.getFinder());
                        long startTime = System.currentTimeMillis();
                        int ret = ocrManager.initEngine();
                        if (ret == 1) {
                            startBCRTime = System.currentTimeMillis() - startTime;    //	初始化时间
                        } else {
                            if (ret == 100) {
                                ToastManager.show(getBaseContext(), "引擎过期！", Toast.LENGTH_SHORT);
                            } else if (ret == 200) {
                                ToastManager.show(getBaseContext(), "授权失败！", Toast.LENGTH_SHORT);
                            } else {
                                ToastManager.show(getBaseContext(), "引擎初始化失败=" + ret, Toast.LENGTH_SHORT);
                            }
                            ocrManager.closeEngine();
                            ocrManager = null;
                            CameraActivity.this.finish();
                            return;
                        }

                    }
                    if (!isAutomatic) {//如果是手动拍照  就停止
                        return;
                    }
                    if (ocrManager.isSetYuvWH()) {
                        ocrManager.setYuvWidthAndHeight(cameraManager.getPreviewWidth(), cameraManager.getPreviewHeight());
                    }
                    byte[] data_p = (byte[]) msg.obj;
                    if (data_p != null && data_p.length > 0) {
                        new RecognitionThread(mHandler, data_p, ocrManager, rect,
                                false, isBlurOn, "").start();
                    } else {
                        isManaulIn = false;
                        isAutoIn = false;
                        finderView.setLineRect(0);
                        ToastManager.show(getBaseContext(), "相机出现问题，请重启手机！", Toast.LENGTH_SHORT);
                        progressBar.setVisibility(View.GONE);
                        mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, rightNow);
                    }
                    break;
                case UtilApp.RECOGN_OK:
                    Logger.d("RECOGN_OK");
                    ResultInfo resultInfo = (ResultInfo) msg.obj;
                    cameraManager.initDisplay();
                    switch (resultInfo.getResultType()) {
                        case UtilApp.RESULT_TYPE_BLUR:
                            if (isManaulIn) {
                                return;
                            }
                            progressBar.setVisibility(View.GONE);
                            autoFoucs = true;
                            mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, rightNow);
                            break;
                        case UtilApp.RESULT_TYPE_NO_IDCARD:
                            if (isManaulIn) {
                                return;
                            }
                            mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, rateTime);
                            progressBar.setVisibility(View.GONE);
                            iv.setVisibility(View.GONE);
                            progressBar.setVisibility(View.GONE);
                            finderView.setLineRect(0);
                            break;
                        case UtilApp.RESULT_TYPE_NO_INRECT:
                            if (isManaulIn) {
                                return;
                            }
                            progressBar.setVisibility(View.GONE);
                            mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, rightNow);
                            tipView.setText("请将快递单正面置于此区域尝试对齐边缘");
                            break;
                        case UtilApp.RESULT_TYPE_OK:
                            Logger.d("RESULT_TYPE_OK");
                            manulRemove();
                            isStop = true;
                            progressBar.setVisibility(View.GONE);
                            iv.setVisibility(View.GONE);
                            tipView.setVisibility(View.GONE);
                            cameraManager.pauseDisplay();
                            validate(resultInfo);
                            break;
                        case UtilApp.RESULT_TYPE_RECONG_FAIL:
                            isAutoIn = false;
                            Log.d(TAG, "----isAutoIn-2-->>>" + isAutoIn);
                            isManaulIn = false;
                            tipView.setText("请将快递单正面置于此区域尝试对齐边缘");
                            progressBar.setVisibility(View.GONE);
                            mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, goonTime);
                            iv.setVisibility(View.GONE);
                            progressBar.setVisibility(View.GONE);
                            break;
                        default:
                            break;
                    }
                    break;
                case UtilApp.RECOGN_FAIL:
                    Logger.d("RECOGN_FAIL");
                    if (isManaulIn) {
                        return;
                    }
                    progressBar.setVisibility(View.GONE);
                    tipView.setText("请将快递单正面置于此区域尝试对齐边缘");
                    mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, goonTime);
                    cameraManager.initDisplay();
                    break;
                case UtilApp.START_AUTOFOCUS:
                    Logger.d("START_AUTOFOCUS");
                    if (isManaulIn) {
                        return;
                    }
                    if (preview) {
                        if (autoFoucs) {
                            cameraManager.autoFoucs();
                            autoFoucs = false;
                        } else {
                            cameraManager.autoFocusAndPreviewCallback();
                        }
                    }
                    break;
                case UtilApp.ONLY_AUTOFOCUS:
                    Logger.d("ONLY_AUTOFOCUS");
                    if (isManaulIn) {
                        return;
                    }
                    cameraManager.autoFoucs();
                    break;
                case UtilApp.RECOGN_LINE_IN_RECT:
                    Logger.d("RECOGN_LINE_IN_RECT");
                    if (isManaulIn) {
                        return;
                    }
                    byte restult = (Byte) msg.obj;
                    if (!isAutomatic) {//如果是手动拍照  就停止
                        return;
                    }
                    finderView.setLineRect(restult);
                    break;
                case UtilApp.LOAD_PIC:
                    Logger.d("LOAD_PIC");
                    if (isManaulIn) {
                        return;
                    }
                    tipView.setText("识别中 ..");
                    break;
                case UtilApp.CAMERA_TAKE_PHOTO://自动
                    Logger.d("CAMERA_TAKE_PHOTO");
                    if (isManaulIn) {
                        return;
                    }
                    if (isDoubleClick(2000)) {
                        Log.d(TAG, "---auto-isDoubleClick-2-->>>");
                        return;
                    }
                    isAutoIn = true;
                    Log.d(TAG, "---auto-CAMERA_TAKE_PHOTO--->>>");

                    mHandler.removeMessages(UtilApp.RECOGN_OK);
                    mHandler.removeMessages(UtilApp.RECOGN_FAIL);
                    mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO);
                    mHandler.removeMessages(UtilApp.START_AUTOFOCUS);
                    mHandler.removeMessages(UtilApp.ONLY_AUTOFOCUS);
                    mHandler.removeMessages(UtilApp.LOAD_PIC);
                    mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_ERROR);
                    mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_OK);
                    mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_DATA_OK);
                    mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_2);
                    mHandler.removeMessages(UtilApp.RECOGN_LINE_NULL);

                    tipView.setText("拍照中 ..");
                    iv.setVisibility(View.GONE);
                    progressBar.setVisibility(View.GONE);
                    cameraManager.takePicture();
                    break;
                case UtilApp.CAMERA_TAKE_PHOTO_2://手动
                    Logger.d("CAMERA_TAKE_PHOTO_2");
                    if (isAutoIn) {
                        return;
                    }
                    if (isDoubleClick(2000)) {
                        Log.d(TAG, "---manaul-isDoubleClick-1-->>>");
                        return;
                    }
                    tipView.setText("拍照中 ..");
                    iv.setVisibility(View.GONE);
                    progressBar.setVisibility(View.GONE);
                    cameraManager.takePicture();
                    break;
                case UtilApp.CAMERA_TAKE_PHOTO_3:
                    Logger.d("CAMERA_TAKE_PHOTO_3");
                    if (isManaulIn || isAutoIn) {
                        return;
                    }
                    isManaulIn = true;
                    mHandler.removeMessages(UtilApp.RECOGN_OK);
                    mHandler.removeMessages(UtilApp.RECOGN_FAIL);
                    mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO);
                    mHandler.removeMessages(UtilApp.START_AUTOFOCUS);
                    mHandler.removeMessages(UtilApp.ONLY_AUTOFOCUS);
                    mHandler.removeMessages(UtilApp.LOAD_PIC);
                    mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_ERROR);
                    mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_OK);
                    mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_DATA_OK);
                    mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_2);
                    mHandler.removeMessages(UtilApp.RECOGN_LINE_NULL);

                    if (ocrManager == null) {
                        ocrManager = new OcrManager();
                        ocrManager.setBlurImage(mBlurImage, mImageCompress);
                        rect = cameraManager.getViewfinder(finderView.getFinder());
                        rect_pthoto = cameraManager.getRectByPhoto(finderView.getFinder());
                        long startTime = System.currentTimeMillis();
                        int ret = ocrManager.initEngine();
                        if (ret == 1) {
                            startBCRTime = System.currentTimeMillis() - startTime;    //	初始化时间
                        } else {
                            if (ret == 100) {
                                ToastManager.show(getBaseContext(), "引擎过期！", Toast.LENGTH_SHORT);
                            } else if (ret == 200) {
                                ToastManager.show(getBaseContext(), "授权失败！", Toast.LENGTH_SHORT);
                            } else {
                                ToastManager.show(getBaseContext(), "引擎初始化失败=" + ret, Toast.LENGTH_SHORT);
                            }
                            ocrManager.closeEngine();
                            ocrManager = null;
                            CameraActivity.this.finish();
                            return;
                        }

                    }

                    cameraManager.autoFoucsAndTakePicture();
                    break;
                case UtilApp.CAMERA_TAKE_PHOTO_OK:
                    break;
                case UtilApp.CAMERA_TAKE_PHOTO_ERROR:
                    Logger.d("CAMERA_TAKE_PHOTO_ERROR");
                    finderView.setLineRect(0);
                    isManaulIn = false;
                    isAutoIn = false;
                    tipView.setText("请将快递单正面置于此区域尝试对齐边缘");
                    progressBar.setVisibility(View.GONE);
                    cameraManager.initDisplay();
                    ToastManager.show(getBaseContext(), "图像质量不好，请重新拍摄！", Toast.LENGTH_SHORT);
                    autoFoucs = true;
                    isManaulIn = false;
                    isAutoIn = false;
                    mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, startTime);
                    break;
                case UtilApp.CAMERA_TAKE_PHOTO_DATA_OK:
                    Logger.d("CAMERA_TAKE_PHOTO_DATA_OK");
                    tipView.setText("识别中 ..");
                    progressBar.setVisibility(View.VISIBLE);
                    byte[] data = (byte[]) msg.obj;
                    if (data == null || data.length <= 0) {
                        isManaulIn = false;
                        isAutoIn = false;
                        ToastManager.show(getBaseContext(), "相机出现问题，请重启手机！！", Toast.LENGTH_SHORT);
                        tipView.setText("请将快递单正面置于此区域尝试对齐边缘");
                        progressBar.setVisibility(View.GONE);
                        cameraManager.initDisplay();
                        mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, rightNow);
                        return;
                    }
                    startRecogTime = System.currentTimeMillis();
                    pictruePath = filePath + startRecogTime + ".jpg";
                    new RecognitionThread(mHandler, data, ocrManager, rect_pthoto,
                            true, isBlurOn, pictruePath).start();
                    break;
                default:
                    tipView.setText("请将快递单正面置于此区域尝试对齐边缘");
                    progressBar.setVisibility(View.GONE);
                    isManaulIn = false;
                    isAutoIn = false;
                    cameraManager.initDisplay();
                    ToastManager.show(getBaseContext(), "-->" + msg.what, Toast.LENGTH_SHORT);
                    mHandler.sendEmptyMessageDelayed(UtilApp.START_AUTOFOCUS, startTime);
                    autoFoucs = true;
                    ToastManager.show(getBaseContext(), "图像质量不好，请重新拍摄！", Toast.LENGTH_SHORT);
                    break;
            }
        }

    };

    private long lastClickTime;

    /**
     * 是否双击
     * 防止照相机拍照按钮双击卡住
     *
     * @return
     */
    public boolean isDoubleClick(long mTime) {
        long time = System.currentTimeMillis();
        if ((time - lastClickTime) < mTime) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        Log.d(TAG, "surfaceCreated");
        if (!cameraManager.cameraOpened()) {
            cameraManager.openCamera();
            setParameters();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        // TODO Auto-generated method stub
        if (holder.getSurface() == null) {
            Log.d(TAG, "holder.getSurface() == null");
            return;
        }
        Log.v(TAG, "surfaceChanged. w=" + width + ". h=" + height);
        surfaceHolder = holder;
        cameraManager.setPreviewDisplay(surfaceHolder);
        cameraManager.initDisplay();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        Log.d(TAG, "surfaceDestroyed");
        cameraManager.closeCamera();
        surfaceHolder = null;
    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
        mHandler.removeMessages(UtilApp.RECOGN_OK);
        mHandler.removeMessages(UtilApp.RECOGN_FAIL);
        mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO);
        mHandler.removeMessages(UtilApp.START_AUTOFOCUS);
        mHandler.removeMessages(UtilApp.ONLY_AUTOFOCUS);
        mHandler.removeMessages(UtilApp.LOAD_PIC);
        mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_ERROR);
        mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_OK);
        mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_DATA_OK);
        mHandler.removeMessages(UtilApp.CAMERA_TAKE_PHOTO_2);
        mHandler.removeMessages(UtilApp.RECOGN_LINE_NULL);

        if (cameraManager != null) {
            try {
                cameraManager.closeCamera();
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void onComplete() {
        isStop = true;
        if (mKyeDialog != null && mKyeDialog.isShowing()) {
            mKyeDialog.dismiss();
        }
    }

    @Override
    public void onLoading() {
        if (mKyeDialog == null) {
            mKyeDialog = new KyeProgressDialog.Builder(CameraActivity.this).build();
        }
        mKyeDialog.show();
    }

    @Override
    public void onLoaded(OpenApiResult<ValidateWaybillUploadResultBean> result) {
        if (result != null && result.getData() != null) {
            ValidateWaybillUploadResultBean validateWaybillUploadResultBean = result.getData();
            if (validateWaybillUploadResultBean.getType() == 1) {
                WaybillPhotograhbean waybillPhotograhbean = new WaybillPhotograhbean();
                waybillPhotograhbean.setId(startRecogTime);
                waybillPhotograhbean.setImagePath(pictruePath);
                waybillPhotograhbean.setWaybillNumber(mCurrentWaybill);
                photograghList.add(waybillPhotograhbean);
                resultIntent.putExtra(ARG_DATA_RESULT, (Serializable) photograghList);
                setResult(RESULT_OK, resultIntent);

                ivRemake.setVisibility(View.VISIBLE);
                ivContinue.setVisibility(View.VISIBLE);
                ivFinishImage.setVisibility(View.VISIBLE);
                Glide.with(CameraActivity.this)
                        .load("file:///" + pictruePath)
                        .into(ivFinishImage);
                ToastManager.show(CameraActivity.this, R.string.waybill_take_photo_success, Toast.LENGTH_SHORT);
            } else {
                showHorizontalDialog(result.getMsg(), hideCancle, true, "取消", "确定");
            }
        }
    }

    @Override
    public void onApiError(String msg) {
        isStop = true;
        ImageUtils.deleteFile(pictruePath);
        ToastManager.show(CameraActivity.this, msg, Toast.LENGTH_SHORT);
        if (mKyeDialog != null && mKyeDialog.isShowing()) {
            mKyeDialog.dismiss();
        }
        ivRemake.setVisibility(View.VISIBLE);
        ivContinue.setVisibility(View.VISIBLE);
        ivFinishImage.setVisibility(View.VISIBLE);
    }

    @Override
    public void onOtherError(String msg) {
        isStop = true;
        ImageUtils.deleteFile(pictruePath);
        ToastManager.show(CameraActivity.this, msg, Toast.LENGTH_SHORT);
        if (mKyeDialog != null && mKyeDialog.isShowing()) {
            mKyeDialog.dismiss();
        }
        ivRemake.setVisibility(View.VISIBLE);
        ivContinue.setVisibility(View.VISIBLE);
        ivFinishImage.setVisibility(View.VISIBLE);
    }
}
